#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::MainWindow(QTcpSocket* s, QString Id, QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    UIDesign::setMainWindowUI(ui->centralwidget);
    UIDesign::setTabUI(ui->tabWidget);
    UIDesign::setListWidgetUI(ui->groupList);
    UIDesign::setListWidgetUI(ui->listWidget);
    UIDesign::setMainButtonUIFromLeft(ui->addFriend);
    UIDesign::setMainButtonUIFromLeft(ui->deleteFriend);
    UIDesign::setMainButtonUIFromLeft(ui->confirmFriend);
    UIDesign::setMainButtonUIFromRight(ui->createGroup);
    UIDesign::setMainButtonUIFromRight(ui->exitGroup);
    UIDesign::setMainButtonUIFromRight(ui->inviteGroup);
    UIDesign::setMainButtonUIFromRight(ui->joinGroup);
    UIDesign::setMainButtonUIFromRight(ui->pushButton);
    UIDesign::setMainButtonUIFromLeft(ui->closeButton);
    UIDesign::setTextListUI(ui->lineEdit);
    UIDesign::setContentListUI(ui->showWindow);

    this->setWindowTitle("聊天界面");
    sock = s;
    //updatefunc();


    ID = Id;
    current_Row = -1;
    connect(this, SIGNAL(FriendListUpdated()), this, SLOT(PerformUpdateGroupList()));
    disconnect(s, SIGNAL(readyRead()), 0, 0);
    updateFriendList();

    sock_read = new QTcpSocket();
    sock_read->connectToHost("10.172.159.112", 9988);
    sock_read->write(ID.toUtf8());
    //disconnect(s, SIGNAL(readyRead()), 0, 0);
    connect(sock_read, SIGNAL(readyRead()), this, SLOT(hadrecv()));
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::PerformUpdateGroupList()
{
    connect(this, SIGNAL(GroupListUpdated()), this, SLOT(PerformUpdateP2PList()));
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    updateGroupList();

}

void MainWindow::PerformUpdateP2PList()
{
    connect(this, SIGNAL(P2PChatUpdated()), this, SLOT(PerformUpdateP2GList()));
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    update_P2P_ChattingList();
}

void MainWindow::PerformUpdateP2GList()
{
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    update_P2G_ChattingList();
}

void MainWindow::on_pushButton_clicked()
{
    //QString sendData = ui->lineEdit->text();

    //发送信息的格式为#sd|myID|targetID|sendData

    //QString temp = "#sd" + "|" + ID +


    //sock->write(sendData.toUtf8());
}

void MainWindow::hadrecv()
{
    QByteArray recvorder = sock_read->readAll();
    QString temp(recvorder);
    QString cmp("con_test");
    if(temp == cmp)
    {
        qDebug() << "connection confirmed!";
        sock_read->write(recvorder);
        return ;
    }
    QJsonParseError err;
    QJsonDocument document = QJsonDocument::fromJson(recvorder, &err);
    if(err.error == QJsonParseError::NoError)
    {
        QJsonObject request = document.object();
        QJsonValue Rorder = request.value("order");
        int order = Rorder.toInt();
        qDebug() << order;
        switch(order)
        {
            case 98:
            {
                qDebug() << order;
                qDebug() << "recieve group message";
                QJsonValue Rmesg = request.value("mesg");
                QJsonObject mesg = Rmesg.toObject();
                QJsonValue Rtimestamp = mesg.value("timestamp");
                QJsonValue Rtext = mesg.value("text");
                QJsonValue Rsd_id = mesg.value("sd_id");
                QJsonValue Rgp_id = mesg.value("gp_id");
                QJsonValue Rsd_name = mesg.value("sd_name");
                QString timestamp = Rtimestamp.toString();
                QString text = Rtext.toString();
                QString sd_id = Rsd_id.toString();
                QString gp_id = Rgp_id.toString();
                QString sd_name = Rsd_name.toString();
                QString qtemp("group");
                localProcess::writeChat(sd_id, sd_name, gp_id, text, timestamp, qtemp, ID);

                qDebug() << "----------------------------";
                qDebug() << mesg ;
                qDebug() << "GroupReceive confirmed";
                qDebug() << "----------------------------";



                int cursor = 0;
                while(cursor != listGroupId.size() && listGroupId[cursor] != gp_id)cursor ++;
                if(cursor == listGroupId.size())
                {
                    QString content1 = "未知群聊正试图与您进行通信\n";
                    QString content2 = " : ";
                    QString content3 = content1 + sd_id + content2 + text;
                    QMessageBox::information(this, "提示", content3);
                    return;
                }
                if(ui->groupList->currentRow() == cursor && ui->tabWidget->currentIndex() == 1)
                {
                    addWig(sd_name, sd_id, timestamp, text);
                    qDebug() << "已打开接受群界面";
                    connect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(deliverGroup()));
                    return ;
                }
                else
                {
                    //修改颜色

                    UIDesign::setAlarmListWidgetItem(ui->groupList->item(cursor));
                }

                break;
            }
            case 97:
            {
                qDebug() << order;
                qDebug() << "recieve private message";
                QJsonValue Rmesg = request.value("mesg");
                QJsonObject mesg = Rmesg.toObject();
                QJsonValue Rtimestamp = mesg.value("timestamp");
                QJsonValue Rtext = mesg.value("text");
                QJsonValue Rsd_id = mesg.value("sd_id");

                QString timestamp = Rtimestamp.toString();
                QString text = Rtext.toString();
                QString sd_id = Rsd_id.toString();
                int cursor = 0;
                while(cursor != listId.size() && listId[cursor] != sd_id)cursor ++;
                if(cursor == listId.size())
                {
                    QString content1 = "未知id正试图与您进行通信\n";
                    QString content2 = " : ";
                    QString content3 = content1 + sd_id + content2 + text;
                    QMessageBox::information(this, "提示", content3);
                    return;
                }

                QString qtemp("friend");
                localProcess::writeChat(sd_id, "", sd_id, text, timestamp, qtemp, ID);

                qDebug() << "----------------------------";
                qDebug() << mesg ;
                qDebug() << "FriendReceive confirmed";
                qDebug() << "----------------------------";





                if(ui->listWidget->currentRow() == cursor && ui->tabWidget->currentIndex() == 0)
                {
                    addWig(listName[cursor], sd_id, timestamp, text);
                    qDebug() << "已打开对应发送者聊天界面";
                    connect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(deliver()));
                    return ;
                }
                else
                {
                    //修改颜色
                    qDebug() << "changeColor";
                    UIDesign::setAlarmListWidgetItem(ui->listWidget->item(cursor));
                }

                break;
            }
            case 96:
            {
                qDebug() << "recieve friend query   ---untreated";


                QJsonValue Rmesg = request.value("mesg");
                QJsonObject mesg = Rmesg.toObject();
                QJsonValue Rsd_id = mesg.value("sd_id");
                QJsonValue Rsd_name = mesg.value("sd_name");
                QJsonValue Rstatus = mesg.value("status");
                QString sd_id = Rsd_id.toString();
                QString sd_name = Rsd_name.toString();
                bool status = Rstatus.toBool();
                if(!status)
                {
                    deleterec(sd_id);
                    QString context1 = "你的好友申请被拒绝：to ";
                    context1 = context1 + sd_name;
                    QMessageBox::information(this, "提示", context1);
                }

                break;


            }
            case 95:
            {
                qDebug() << order;
                qDebug() << "recieve group query";
                QJsonValue Rmesg = request.value("mesg");
                QJsonObject mesg = Rmesg.toObject();
                QJsonValue Rgp_id = mesg.value("gp_id");
                QJsonValue Rgp_name = mesg.value("gp_name");
                QString gp_id = Rgp_id.toString();
                QString gp_name = Rgp_name.toString();
                joinGroupRec(gp_name, gp_id);
                qDebug() << "enter group" + gp_name;

                break;
            }
            default:
            {
                qDebug() << "未知的order";
            }

        }
    }
    else qDebug() << "解包错误";
}

void MainWindow::on_closeButton_clicked()
{
    this->close();
    sock->disconnectFromHost();
    Login* login = new Login();
    login->show();
}


void MainWindow::on_addFriend_clicked()//添加好友
{
    friendAdd *fa = new friendAdd(sock, ID);
    fa->show();
    //创建添加好友窗体
    qDebug() << "clicked";
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    connect(fa, SIGNAL(addfriendclose(QString, QString, QString)), this, SLOT(createrec(QString, QString, QString)));
}


void MainWindow::createrec(QString uName, QString unId, QString nickname)
{
    creatingNickname = nickname;
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    qDebug() << uName << "|" << unId << "|" << nickname;
    int flag = 0;
    for(int i = 0; i < listId.size(); i ++)
    {
        if(unId == listId[i])
        {
            flag = 1;
            break;
        }
    }
    if(flag == 0)
    {
        QString temp = nickname + " (" + unId + ")\n" + uName;
        ui->listWidget->addItem(temp);
        listId << unId;
        listName << uName;
        listNickName << nickname;
        localProcess::newChatFriend(unId, "friend", ID);

    }
    else
    {
        QMessageBox::information(this, "提示", "已经有此好友，无需添加");
    }

    for(int i = 0; i < listId.size(); i ++)
    {
        qDebug() << listName[i] << "|" << listId[i] << listNickName[i];
    }
}

void MainWindow::on_listWidget_itemDoubleClicked(QListWidgetItem *item)
{
    disconnect(ui->pushButton, SIGNAL(clicked(bool)), 0, 0);
    ui->showWindow->clear();
    UIDesign::setNormalListWidgetItem(item);
    int line = ui->listWidget->currentRow();
    communicationId = listId[line];
    qDebug() << line << "|" << communicationId;
    QList<QList<QString>> info = localProcess::readHistory(communicationId, "friend", ID);
    for(int i=0;i<info.size();i++){
        //id|time|content
        if(info[i][0] == ID){
            addWig("我", ID, info[i][1], info[i][2]);
        }else{
            addWig(listNickName.at(line), info[i][0], info[i][1], info[i][2]);
        }
    }
    connect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(deliver()));
}
void MainWindow::deliver()
{
    if(ui->lineEdit->document()->toPlainText().length()<1){
        QMessageBox::warning(this, "提示", "发送内容不能为空");
        return ;
    }else if(ui->lineEdit->document()->toPlainText().length()>160){
        QMessageBox::warning(this, "提示", "发送字数超过限制");
        return ;
    }
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    connect(sock, SIGNAL(readyRead()), this, SLOT(testDeliver()));
    QJsonObject request;
    request.insert("order", 20);
    request.insert("myid", ID);
    QJsonObject data;
    data.insert("to_id", communicationId);
    data.insert("mesg", ui->lineEdit->document()->toPlainText());
    request.insert("data", data);
    QJsonDocument document(request);
    QByteArray byteRequest = document.toJson();
    sock->write(byteRequest);


    //发送信息的格式为#sd|myID|targetID|sendData

}
void MainWindow::testDeliver()
{
    QByteArray feedback = sock->readAll();

    QJsonParseError err;

    QJsonDocument document = QJsonDocument::fromJson(feedback, &err);
    if(err.error == QJsonParseError::NoError)
    {
        QJsonObject request = document.object();
        QJsonValue Rstatus = request.value("status");
        bool status = Rstatus.toBool();
        if(status)
        {
            QJsonValue Rmesg = request.value("mesg");
            QJsonObject mesg = Rmesg.toObject();
            QJsonValue Rtimestamp = mesg.value("timestamp");
            QString timestamp = Rtimestamp.toString();
            localProcess::writeChat(ID, "", communicationId, ui->lineEdit->document()->toPlainText(),timestamp, "friend", ID);
            addWig("我", ID, timestamp, ui->lineEdit->document()->toPlainText());
            ui->lineEdit->clear();
        }
        else
        {
            QMessageBox::information(this, "提示", "发送失败，请重试");
        }
    }
    else
    {
        qDebug() << "解包失败";
    }


    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    //发送信息的返回值为 #rd|myID|targetID|0（失败）/1（成功）|time


}

void MainWindow::on_deleteFriend_clicked()
{
    frienddelete *fd = new frienddelete(sock, ID);
    fd->show();
    //创建删除好友窗体
    qDebug() << "clicked";
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    connect(fd, SIGNAL(deletefriendclose(QString)), this, SLOT(deleterec(QString)));
}

void MainWindow::deleterec(QString unId)
{
    qDebug() << unId;
    int cursor = 0;
    while(cursor != listId.size() && listId[cursor] != unId)cursor ++;
    if(cursor != listId.size())
    {
        localProcess::deleteHistory(unId, "friend", ID);
        ui->listWidget->takeItem(cursor);
        listId.removeAt(cursor);
        listName.removeAt(cursor);
        listName.removeAt(cursor);
    }
}

void MainWindow::on_createGroup_clicked()
{
    groupCreate *gc = new groupCreate(sock, ID);
    gc->show();
    qDebug() << "Clicked";
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    connect(gc, SIGNAL(creategroupclose(QString, QString)), this, SLOT(creategrouprec(QString, QString)));
}
void MainWindow::creategrouprec(QString gName, QString gID)
{
    qDebug() << gName << "|" << gID;
    int flag = 0;
    for(int i = 0; i < listId.size(); i ++)
    {
        if(gID == listId[i])
        {
            flag = 1;
            break;
        }
    }
    if(flag == 0)
    {
        QString temp = gName + " (" + gID + ")";
        ui->groupList->addItem(temp);
        listGroupId << gID;
        listGroupName << gName;
        listGroupVerify << "1";

        localProcess::newChatFriend(gID, "group", ID);

        //xml本地化

        //newChatFriend(unId);
    }
}




void MainWindow::on_joinGroup_clicked()
{
    groupJoin *gj = new groupJoin(sock, ID);
    gj->show();
    qDebug() << "Clicked";
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    connect(gj, SIGNAL(joinGroupClose(QString,QString)), this, SLOT(joinGroupRec(QString,QString)));
}
void MainWindow::joinGroupRec(QString gName, QString gID)
{
    qDebug() << gName << "|" << gID;
    int flag = 0;
    for(int i = 0; i < listId.size(); i ++)
    {
        if(gID == listId[i])
        {
            flag = 1;
            break;
        }
    }
    if(flag == 0)
    {
        QString temp = gName + " (" + gID + ")";
        ui->groupList->addItem(temp);
        listGroupId << gID;
        listGroupName << gName;
        listGroupVerify << "0";


        //xml本地化
        localProcess::newChatFriend(gID, "group", ID);
        //newChatFriend(unId);
    }
}

void MainWindow::on_inviteGroup_clicked()
{
    if(ui->tabWidget->currentIndex() == 0)
    {
        QMessageBox::information(this, "提示", "请打开群聊界面进行选择");
        return;
    }
    if(ui->groupList->count()<1){
        QMessageBox::information(this, "提示", "你还没有加入群聊");
        return;
    }
    //要获取当前群聊
    groupInvite *gi = new groupInvite(sock, ID, gID);
    gi->show();
    qDebug() << "Clicked";
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
}



void MainWindow::updateFriendList()
{
    qDebug() << "1";
    listId.clear();
    listName.clear();
    listNickName.clear();
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    connect(sock, SIGNAL(readyRead()), this, SLOT(decodeFriendList()));
    qDebug() << "1";
    QJsonObject request;
    request.insert("order", 30);
    request.insert("myid", ID);
    QJsonObject data;
    request.insert("data", data);
    QJsonDocument temp(request);
    QByteArray byte_request = temp.toJson();
    sock->write(byte_request);
    qDebug() << "1";
}


void MainWindow::decodeFriendList()
{
    QByteArray feedback = sock->readAll();
    qDebug() << "2";
    QJsonParseError feedback_error;
    QJsonDocument feedback_doc = QJsonDocument::fromJson(feedback, &feedback_error);
    if(feedback_error.error == QJsonParseError::NoError)
    {
        QJsonObject RRrequest = feedback_doc.object();
        QJsonValue Rrequest = RRrequest.value("mesg");
        QJsonObject request = Rrequest.toObject();
        QJsonValue Rnum = request.value("num");
        int num = Rnum.toInt();
        qDebug() << num;
        if(num == 0)
        {
            emit FriendListUpdated();
            return ;
        }
        else
        {
            QJsonValue Rfriends = request.value("friends");
            QJsonArray friends = Rfriends.toArray();
            for(int i = 0; i < num; i ++)
            {
                QJsonValue Rtemp = friends.at(i);
                QJsonObject temp = Rtemp.toObject();
                QJsonValue Rname = temp.value("name");
                QJsonValue Rid = temp.value("id");
                QJsonValue Rnickname = temp.value("nickname");
                QString name = Rname.toString();

                QString id = Rid.toString();
                QString nickname = Rnickname.toString();
                qDebug() << name << "|" << id << "|" << nickname;
                QString qtemp = nickname + " (" + id + ")\n" + name;
                ui->listWidget->addItem(qtemp);
                listId << id;
                listName << name;
                listNickName << nickname;
            }
        }
    }
    else
    {
        QMessageBox::information(this, "提示", "服务器发送的数据包有错误");
    }
    emit FriendListUpdated();
}

void MainWindow::updateGroupList()
{

    listGroupId.clear();
    listGroupName.clear();
    listGroupVerify.clear();
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    connect(sock, SIGNAL(readyRead()), this, SLOT(decodeGroupList()));
    QJsonObject request;
    request.insert("order", 31);
    request.insert("myid", ID);
    QJsonObject data;
    request.insert("data", data);
    QJsonDocument temp(request);
    QByteArray byte_request = temp.toJson();
    sock->write(byte_request);
}
void MainWindow::decodeGroupList()
{
    QByteArray feedback = sock->readAll();
    QJsonParseError feedback_error;
    QJsonDocument feedback_doc = QJsonDocument::fromJson(feedback, &feedback_error);
    if(feedback_error.error == QJsonParseError::NoError)
    {
        QJsonObject RRrequest = feedback_doc.object();
        QJsonValue Rrequest = RRrequest.value("mesg");
        QJsonObject request = Rrequest.toObject();
        QJsonValue Rnum = request.value("num");
        int num = Rnum.toInt();
        if(num == 0)
        {
            emit GroupListUpdated();
            return ;
        }
        else
        {
            QJsonValue Rgroup = request.value("group");
            QJsonArray group = Rgroup.toArray();
            for(int i = 0; i < num; i ++)
            {
                QJsonValue Rtemp = group.at(i);
                QJsonObject temp = Rtemp.toObject();
                QJsonValue Rgroup_name = temp.value("group_name");
                QJsonValue Rid = temp.value("id");
                QJsonValue Rboss = temp.value("boss");
                QString group_name = Rgroup_name.toString();
                QString id = Rid.toString();
                bool boss = Rboss.toBool();
                if(boss)
                {
                    QString qtemp = group_name + " (" + id + ")";
                    ui->groupList->addItem(qtemp);
                    listGroupId << id;
                    listGroupName << group_name;
                    listGroupVerify << "1";
                }
                else
                {
                    QString qtemp = group_name + " (" + id + ")";
                    ui->groupList->addItem(qtemp);
                    listGroupId << id;
                    listGroupName << group_name;
                    listGroupVerify << "0";
                }
            }
        }
    }
    else
    {
        QMessageBox::information(this, "提示", "服务器发送的数据包有错误");
    }
    emit GroupListUpdated();
}

void MainWindow::update_P2P_ChattingList()
{
    disconnect(sock, SIGNAL(readyRead()), 0, 0);

    int friendsize = listId.size();
    for(int i = 0; i < friendsize; i ++)
    {
        update_P2P_ChattingList_SINGLE(listId[i]);

        disconnect(sock, SIGNAL(readyRead()), 0, 0);

    }
    emit P2PChatUpdated();
}

void MainWindow::update_P2P_ChattingList_SINGLE(QString targetID)
{


    targetID_for_updataP2P = targetID;
    QJsonObject request;
    request.insert("order", 32);
    request.insert("myid", ID);
    QJsonObject data;
    data.insert("targetid", targetID_for_updataP2P);
    QString qtemp("friend");
    data.insert("timestamp", localProcess::getLastTime(targetID, qtemp, ID));
    request.insert("data", data);
    QJsonDocument temp(request);
    QByteArray byte_request = temp.toJson();
    sock->write(byte_request);
    qDebug() << "1";
    qDebug() << "2";
    //connect(sock, SIGNAL(readyRead()), this, SLOT(decode_P2P_ChattingList()));
    sock->waitForReadyRead();
    QByteArray feedback = sock->readAll();
    QJsonParseError feedback_error;
    QJsonDocument feedback_doc = QJsonDocument::fromJson(feedback, &feedback_error);
    if(feedback_error.error == QJsonParseError::NoError)
    {
        QJsonObject RRrequest = feedback_doc.object();
        QJsonValue Rrequest = RRrequest.value("mesg");
        QJsonObject request = Rrequest.toObject();
        QJsonValue Rnum = request.value("num");
        int num = Rnum.toInt();
        qDebug() << "4" << "|" << num;
        if(num == 0);
        else
        {
            QJsonValue Rmesg = request.value("mesg");
            QJsonArray mesg = Rmesg.toArray();
            QList<QString> sender_id;
            QList<QString> sender_name;
            QList<QString> send_content;
            QList<QString> send_timestamp;
            qDebug() << "5";
            for(int i = 0; i < num; i ++)
            {
                QJsonValue Rtemp = mesg.at(i);
                QJsonObject temp = Rtemp.toObject();
                QJsonValue Rcontent = temp.value("content");
                QJsonValue Rtimestamp = temp.value("timestamp");
                QString content = Rcontent.toString();
                QString timestamp = Rtimestamp.toString();
                //int cursor = 0;

                sender_id<<targetID_for_updataP2P;
                send_content<<content;
                send_timestamp<<timestamp;

                //while(cursor != listId.size() && listId[cursor] != targetID_for_updataP2P)cursor ++;
                //localProcess::writeChat(targetID_for_updataP2P, listName[cursor], targetID_for_updataP2P, content, timestamp, qmode);
            }

            qDebug() << "6";
            QString qmode("friend");
            localProcess::writeChat(sender_id, sender_name, targetID_for_updataP2P, send_content, send_timestamp, qmode, ID);
            qDebug() << "7";
        }
    }
    else
    {
        QMessageBox::information(this, "提示", "服务器发送的数据包有错误");
    }
    emit finish();
    qDebug() << "3";
}

void MainWindow::update_P2G_ChattingList()
{
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    int groupsize = listGroupId.size();
    for(int i = 0; i < groupsize; i ++)
    {
        update_P2G_ChattingList_SINGLE(listGroupId[i]);
        disconnect(sock, SIGNAL(readyRead()), 0, 0);
    }
}


void MainWindow::update_P2G_ChattingList_SINGLE(QString groupID)
{

    GroupID_for_updataP2G = groupID;
    QJsonObject request;
    request.insert("order", 33);
    request.insert("myid", ID);
    QJsonObject data;
    data.insert("groupid", GroupID_for_updataP2G);
    QString qtemp("group");
    data.insert("timestamp", localProcess::getLastTime(groupID, qtemp, ID));
    request.insert("data", data);
    QJsonDocument temp(request);
    QByteArray byte_request = temp.toJson();
    sock->write(byte_request);
    sock->waitForReadyRead();
    QByteArray feedback = sock->readAll();
    QJsonParseError feedback_error;
    QJsonDocument feedback_doc = QJsonDocument::fromJson(feedback, &feedback_error);
    if(feedback_error.error == QJsonParseError::NoError)
    {
        QJsonObject RRrequest = feedback_doc.object();
        QJsonValue Rrequest = RRrequest.value("mesg");
        QJsonObject request = Rrequest.toObject();
        QJsonValue Rnum = request.value("num");
        int num = Rnum.toInt();
        if(num == 0)return ;
        else
        {
            QList<QString> send_id;
            QList<QString> send_name;
            QList<QString> send_content;
            QList<QString> send_timestamp;

            QJsonValue Rmesg = request.value("mesg");
            QJsonArray mesg = Rmesg.toArray();
            for(int i = 0; i < num; i ++)
            {
                QJsonValue Rtemp = mesg.at(i);
                QJsonObject temp = Rtemp.toObject();
                QJsonValue Rcontent = temp.value("content");
                QJsonValue Rtimestamp = temp.value("timestamp");
                QJsonValue Rsender_id = temp.value("sender_id");
                QJsonValue Rsender_name = temp.value("sender_name");
                QString content = Rcontent.toString();
                QString timestamp = Rtimestamp.toString();
                QString sender_id = Rsender_id.toString();
                QString sender_name = Rsender_name.toString();

                send_id<<sender_id;
                send_name<<sender_name;
                send_content<<content;
                send_timestamp<<timestamp;

                //int cursor = 0;

                //while(cursor != listGroupId.size() && listGroupId[cursor] != GroupID_for_updataP2G)cursor ++;
                //localProcess::writeChat(sender_id, sender_name, GroupID_for_updataP2G, content, timestamp, qmode);
            }
            QString qmode("group");
            localProcess::writeChat(send_id, send_name, GroupID_for_updataP2G, send_content, send_timestamp, qmode, ID);
        }
    }
    else
    {
        QMessageBox::information(this, "提示", "服务器发送的数据包有错误");
    }
}






void MainWindow::on_exitGroup_clicked()
{
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    connect(sock, SIGNAL(readyRead()), this, SLOT(ProcessExitGroup()));
    if(ui->tabWidget->currentIndex() == 0)
    {
        QMessageBox::information(this, "提示", "请打开群聊界面进行选择");
    }
    else if(listGroupId.size() == 0) QMessageBox::information(this, "提示", "您没有群聊");

    else
    {
        current_Row = ui->groupList->currentRow();
        if(current_Row >= listGroupId.size() || current_Row < 0)
        {
            QMessageBox::information(this, "提示", "请重新选择");
        }

        int ret = QMessageBox::information(this, "提示", "你想退出群:" + listGroupName[current_Row] + " 吗？", QMessageBox::Yes, QMessageBox::No);
        if(ret == QMessageBox::Yes)
        {
            disconnect(sock, SIGNAL(readyRead()), 0 , 0);
            connect(sock, SIGNAL(readyRead()), this, SLOT(ProcessExitGroup()));
            QJsonObject request;
            request.insert("order", 10);
            request.insert("myid", ID);
            QJsonObject data;
            data.insert("gp_id", gID);
            request.insert("data", data);
            qDebug() << request;
            QJsonDocument document(request);
            QByteArray byteReq = document.toJson();
            sock->write(byteReq);

        }
        else
        {
            disconnect(sock, SIGNAL(readyRead()), 0 , 0);
            return ;
        }
    }


}

void MainWindow::ProcessExitGroup()
{
    QByteArray byteRequest;
    byteRequest = sock->readAll();
    QJsonParseError err;
    QJsonDocument document = QJsonDocument::fromJson(byteRequest, &err);
    if(err.error == QJsonParseError::NoError)
    {
        QJsonObject request = document.object();
        QJsonValue Rstatus = request.value("status");
        bool status = Rstatus.toBool();
        if(status)
        {
            localProcess::deleteHistory(gID, "group", ID);

            listGroupId.removeAt(ui->groupList->currentRow());
            listGroupName.removeAt(ui->groupList->currentRow());
            listGroupVerify.removeAt(ui->groupList->currentRow());
            ui->groupList->takeItem(ui->groupList->currentRow());

            QMessageBox::information(this, "提示", "退出成功");
        }
        else
        {
            QMessageBox::information(this, "提示", "退出失败，请重试");
        }
    }
    disconnect(sock, SIGNAL(readyRead()), 0 , 0);
}


void MainWindow::on_groupList_itemClicked(QListWidgetItem *item)
{
    current_Row = ui->groupList->currentRow();
    gID = listGroupId[current_Row];
}

void MainWindow::addWig(QString name, QString fromID, QString time, QString content){

    chatContent* chCo = new chatContent(name, fromID, time, content);
    QListWidgetItem* item = new QListWidgetItem(ui->showWindow);
    ui->showWindow->addItem(item);
    ui->showWindow->setItemWidget(item, chCo);

    item->setSizeHint(QSize(chCo->width(), chCo->height()));
    chCo->design(fromID);
    chCo->show();
    ui->showWindow->scrollToBottom();
    //ui->showWindow->verticalScrollBar()
}

void MainWindow::on_confirmFriend_clicked()
{
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    connect(sock, SIGNAL(readyRead()), this, SLOT(processFriendQuery()));

    QJsonObject request;
    request.insert("order", 34);
    request.insert("myid", ID);
    QJsonObject data;
    request.insert("data", data);
    qDebug() << request;
    QJsonDocument document;
    document.setObject(request);
    QByteArray byteRequest = document.toJson();
    sock->write(byteRequest);
}

void MainWindow::processFriendQuery()
{
    QByteArray byteRequest;
    byteRequest = sock->readAll();
    QJsonParseError err;
    QJsonDocument document = QJsonDocument::fromJson(byteRequest, &err);
    if(err.error == QJsonParseError::NoError)
    {
        QJsonObject RRrequest = document.object();
        QJsonValue Rrequest = RRrequest.value("mesg");
        QJsonObject request = Rrequest.toObject();
        QJsonValue Rnum = request.value("num");
        int num = Rnum.toInt();
        if(num == 0)
        {
            QMessageBox::information(this, "提示", "暂无好友申请");
            return ;
        }
        else
        {
            QJsonValue Rfriend = request.value("friend");
            QJsonArray QueryList = Rfriend.toArray();
            for(int i = 0; i < num; i ++)
            {
                QJsonValue te = QueryList.at(i);
                QJsonObject temp = te.toObject();
                QJsonValue RfriendID = temp.value("userid");
                QJsonValue RfriendName = temp.value("username");
                QString friendID = RfriendID.toString();
                QString friendName = RfriendName.toString();
                QString itemp("有新的好友添加请求 \n Name:");
                int ret = QMessageBox::information(this, "提示", itemp + friendName, QMessageBox::Yes, QMessageBox::No);
                if(ret == QMessageBox::No)
                {
                    QJsonObject request;
                    request.insert("order", 7);
                    request.insert("myid", ID);
                    QJsonObject data;
                    data.insert("to_id", friendID);
                    data.insert("confirm", false);
                    data.insert("nickname", "");
                    request.insert("data", data);
                    qDebug() << request;
                    QJsonDocument document(request);
                    QByteArray byteReq = document.toJson();
                    sock->write(byteReq);
                    QByteArray yes = sock->readAll();
                }
                else
                {
                    setFriendNickname *sfn = new setFriendNickname(friendName, friendID);
                    sfn->show();
                    connect(sfn, SIGNAL(signalSetFriendNickname(QString, QString, QString)), this, SLOT(performAddFriendSendback(QString,QString,QString)));
                }
            }
        }
    }
    else
    {
        QMessageBox::information(this, "警告", "服务器出错");
    }
    disconnect(sock, SIGNAL(readyRead()), 0 , 0);
}

void MainWindow::performAddFriendSendback(QString uName, QString unId, QString nickname)
{
    createrec(uName, unId, nickname);
    QJsonObject request;
    request.insert("order", 7);
    request.insert("myid", ID);
    QJsonObject data;
    data.insert("to_id", unId);
    data.insert("confirm", true);
    data.insert("nickname", nickname);
    request.insert("data", data);
    qDebug() << request;
    QJsonDocument document(request);
    QByteArray byteReq = document.toJson();
    sock->write(byteReq);
    QByteArray yes = sock->readAll();
    localProcess::newChatFriend(unId, "friend", ID);
}

void MainWindow::on_groupList_itemDoubleClicked(QListWidgetItem *item)
{

    disconnect(ui->pushButton, SIGNAL(clicked(bool)), 0, 0);
    ui->showWindow->clear();
    UIDesign::setNormalListWidgetItem(item);
    int line = ui->groupList->currentRow();
    communicationGId = listGroupId[line];
    qDebug() << line << "|" << communicationGId;
    QList<QList<QString>> info = localProcess::readHistory(communicationGId, "group", ID);

    for(int i=0;i<info.size();i++){
        //id|time|content|name
        addWig(info[i][3], info[i][0], info[i][1], info[i][2]);
    }
    connect(ui->pushButton, SIGNAL(clicked(bool)), this, SLOT(deliverGroup()));
}

void MainWindow::deliverGroup()
{
    if(ui->lineEdit->document()->toPlainText().length()<1){
        QMessageBox::warning(this, "提示", "发送内容不能为空");
        return ;
    }else if(ui->lineEdit->document()->toPlainText().length()>160){
        QMessageBox::warning(this, "提示", "发送字数超过限制");
        return ;
    }
    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    connect(sock, SIGNAL(readyRead()), this, SLOT(testDeliverGroup()));
    QJsonObject request;
    request.insert("order", 21);
    request.insert("myid", ID);
    QJsonObject data;
    data.insert("gp_id", communicationGId);
    data.insert("mesg", ui->lineEdit->document()->toPlainText());
    request.insert("data", data);
    QJsonDocument document(request);
    QByteArray byteRequest = document.toJson();
    sock->write(byteRequest);
}

void MainWindow::testDeliverGroup()
{

    QByteArray feedback = sock->readAll();

    QJsonParseError err;

    QJsonDocument document = QJsonDocument::fromJson(feedback, &err);
    if(err.error == QJsonParseError::NoError)
    {
        QJsonObject request = document.object();
        QJsonValue Rstatus = request.value("status");
        bool status = Rstatus.toBool();
        if(status)
        {
            QJsonValue Rmesg = request.value("mesg");
            QJsonObject mesg = Rmesg.toObject();
            QJsonValue Rtimestamp = mesg.value("timestamp");
            QString timestamp = Rtimestamp.toString();

            localProcess::writeChat(ID, "我", communicationGId, ui->lineEdit->document()->toPlainText(), timestamp, "group", ID);
            addWig("我", ID, timestamp, ui->lineEdit->document()->toPlainText());
            ui->lineEdit->clear();
        }
        else
        {
            QMessageBox::information(this, "提示", "群聊已被解散！");
            localProcess::deleteHistory(gID, "group", ID);
            ui->groupList->takeItem(ui->groupList->currentRow());

        }
    }
    else
    {
        qDebug() << "解包失败";
    }


    disconnect(sock, SIGNAL(readyRead()), 0, 0);
    //发送信息的返回值为 #rd|myID|targetID|0（失败）/1（成功）|time
}
